/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import classe.controlador.SetorJpaController;
import classe.controlador.UsuarioJpaController;
import classe.controlador.exceptions.IllegalOrphanException;
import classe.controlador.exceptions.NonexistentEntityException;
import classe.entidade.Setor;
import classe.entidade.Usuario;
import java.util.InputMismatchException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.swing.JOptionPane;

/**
 *
 * @author Pinheiro
 */
public class CadastroUsuario extends javax.swing.JFrame {

    /**
     * Creates new form Usuario
     */
    
    public CadastroUsuario(int id ,String nome, String cpf, String login, String senha){
        initComponents();
        this.setLocationRelativeTo(rootPane);
        
        idUsuario.setText(Integer.toString(id));
        txtNomeUsuario.setText(nome);
        txtCpf.setText(cpf);
        txtLogin.setText(login);
        txtSenha.setText(senha);
        
        botaoSalvarUsuario.setVisible(true);
        botaoCadastrarUsuario.setVisible(false);
        
    }
    public CadastroUsuario() {
        initComponents();
        
        botaoSalvarUsuario.setVisible(false);
        botaoCadastrarUsuario.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtCpf = new javax.swing.JTextField();
        txtLogin = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        botaoCadastrarUsuario = new javax.swing.JButton();
        txtNomeUsuario = new javax.swing.JTextField();
        txtSenha = new javax.swing.JPasswordField();
        limparDadosUsuario = new javax.swing.JButton();
        botaoSalvarUsuario = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        idUsuario = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastrar usuário"));

        txtCpf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCpfActionPerformed(evt);
            }
        });

        txtLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtLoginActionPerformed(evt);
            }
        });

        jLabel1.setText("Nome:");

        jLabel4.setText("Senha:");

        jLabel3.setText("Login:");

        jLabel2.setText("CPF:");

        botaoCadastrarUsuario.setText("Cadastrar");
        botaoCadastrarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCadastrarUsuarioActionPerformed(evt);
            }
        });

        txtNomeUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNomeUsuarioActionPerformed(evt);
            }
        });

        txtSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSenhaActionPerformed(evt);
            }
        });

        limparDadosUsuario.setText("Limpar");
        limparDadosUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                limparDadosUsuarioActionPerformed(evt);
            }
        });

        botaoSalvarUsuario.setText("Salvar");
        botaoSalvarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSalvarUsuarioActionPerformed(evt);
            }
        });

        jLabel5.setText("Id:");

        idUsuario.setEnabled(false);
        idUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idUsuarioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(botaoCadastrarUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoSalvarUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(limparDadosUsuario))
                    .addComponent(txtNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 478, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(txtCpf, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtSenha, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtLogin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(idUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(idUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoCadastrarUsuario)
                    .addComponent(botaoSalvarUsuario)
                    .addComponent(limparDadosUsuario)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(55, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(44, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtNomeUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomeUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNomeUsuarioActionPerformed

    private void botaoCadastrarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarUsuarioActionPerformed
        cadastrarUsuario();
    }//GEN-LAST:event_botaoCadastrarUsuarioActionPerformed

    private void limparDadosUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limparDadosUsuarioActionPerformed
        limparDados();
    }//GEN-LAST:event_limparDadosUsuarioActionPerformed

    private void txtCpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCpfActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCpfActionPerformed

    private void txtLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLoginActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtLoginActionPerformed

    private void txtSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSenhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSenhaActionPerformed

    private void botaoSalvarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarUsuarioActionPerformed
        editarUsuario();
    }//GEN-LAST:event_botaoSalvarUsuarioActionPerformed

    private void idUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_idUsuarioActionPerformed
    
    private void cadastrarUsuario(){
    
        
        Usuario usuario = new Usuario();
        
        if(txtNomeUsuario.getText().equals("") || txtCpf.getText().equals("") || txtLogin.getText().equals("") || txtSenha.equals("")){
        JOptionPane.showMessageDialog(rootPane, "Campo inválido!");
    }
        else
        {
            String nomeUsuario = txtNomeUsuario.getText();
            String loginUsuario = txtLogin.getText();
            String cpfUsuario = txtCpf.getText();
            String senhaUsuario = txtSenha.getText();
            usuario.setNome(nomeUsuario);
            usuario.setLogin(loginUsuario);
            usuario.setSenha(senhaUsuario);
            usuario.setCpf(cpfUsuario);
//            usuario.setId(25);

            if(isCPF(txtCpf.getText()) == true){
                UsuarioJpaController daoUsuario = new UsuarioJpaController();
                daoUsuario.create(usuario);
                JOptionPane.showMessageDialog(rootPane, "Cadastro realizado com sucesso!");
                limparDados();            
        }
        else{
            JOptionPane.showMessageDialog(rootPane, "Digite um CPF válido!");
            
        }
        } 
        
    }
    private boolean validaCPF(String strCpf){
    int iDigito1Aux = 0, iDigito2Aux = 0, iDigitoCPF;
    int iDigito1 = 0, iDigito2 = 0, iRestoDivisao = 0;
    String strDigitoVerificador, strDigitoResultado;
 
    if (! strCpf.substring(0,1).equals("")){
        try{
            strCpf = strCpf.replace('.',' ');
            strCpf = strCpf.replace('-',' ');
            strCpf = strCpf.replaceAll(" ","");
            for (int iCont = 1; iCont < strCpf.length() -1; iCont++) {
                iDigitoCPF = Integer.valueOf(strCpf.substring(iCont -1, iCont)).intValue();
                iDigito1Aux = iDigito1Aux + (11 - iCont) * iDigitoCPF;
                iDigito2Aux = iDigito2Aux + (12 - iCont) * iDigitoCPF;
            }
            iRestoDivisao = (iDigito1Aux % 11);
            if (iRestoDivisao < 2) {
                iDigito1 = 0;
            } else {
                iDigito1 = 11 - iRestoDivisao;
            }
            iDigito2Aux += 2 * iDigito1;
            iRestoDivisao = (iDigito2Aux % 11);
            if (iRestoDivisao < 2) {
                iDigito2 = 0;
            } else {
                iDigito2 = 11 - iRestoDivisao;
            }
            strDigitoVerificador = strCpf.substring(strCpf.length()-2, strCpf.length());
            strDigitoResultado = String.valueOf(iDigito1) + String.valueOf(iDigito2);
            return strDigitoVerificador.equals(strDigitoResultado);
        } catch (Exception e) {
            return false;
        }
    } else {
        return false;
    }
}
    
        public static boolean isCPF(String CPF) {
            
            boolean valor = true;
            if(CPF.length() == 14)
                return valor;
            else
                return valor = false;
// considera-se erro CPF's formados por uma sequencia de numeros iguais
//    if (CPF.equals("00000000000") || CPF.equals("11111111111") ||
//        CPF.equals("22222222222") || CPF.equals("33333333333") ||
//        CPF.equals("44444444444") || CPF.equals("55555555555") ||
//        CPF.equals("66666666666") || CPF.equals("77777777777") ||
//        CPF.equals("88888888888") || CPF.equals("99999999999") ||
//       (CPF.length() != 11)){
//        valor = false;
//        
//    }
//    char dig10, dig11;
//    int sm, i, r, num, peso;
// 
//// "try" - protege o codigo para eventuais erros de conversao de tipo (int)
//    try {
//// Calculo do 1o. Digito Verificador
//      sm = 0;
//      peso = 10;
//      for (i=0; i<9; i++) {             
//// converte o i-esimo caractere do CPF em um numero:
//// por exemplo, transforma o caractere '0' no inteiro 0        
//// (48 eh a posicao de '0' na tabela ASCII)        
//        num = (int)(CPF.charAt(i) - 48);
//        sm = sm + (num * peso);
//        peso = peso - 1;
//      }
// 
//      r = 11 - (sm % 11);
//      if ((r == 10) || (r == 11))
//         dig10 = '0';
//      else dig10 = (char)(r + 48); // converte no respectivo caractere numerico
// 
//// Calculo do 2o. Digito Verificador
//      sm = 0;
//      peso = 11;
//      for(i=0; i<10; i++) {
//        num = (int)(CPF.charAt(i) - 48);
//        sm = sm + (num * peso);
//        peso = peso - 1;
//      }
// 
//      r = 11 - (sm % 11);
//      if ((r == 10) || (r == 11))
//         dig11 = '0';
//      else dig11 = (char)(r + 48);
// 
//// Verifica se os digitos calculados conferem com os digitos informados.
//      if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
//         return valor;
//      else valor =false;
//    } catch (InputMismatchException erro) {
//        valor = false;
//    }
//    return valor;
    
  }
 
  public static String imprimeCPF(String CPF) {
    return(CPF.substring(0, 3) + "." + CPF.substring(3, 6) + "." +
      CPF.substring(6, 9) + "-" + CPF.substring(9, 11));
  }





    private void limparDados() {
       
       txtCpf.setText(null);
       txtLogin.setText(null);
       txtNomeUsuario.setText(null);
       txtSenha.setText(null);
    }
    
    private void editarUsuario() {
        
        UsuarioJpaController daoUsuario = new UsuarioJpaController();
        
        try {
            Usuario usuario = new Usuario();
            usuario.setCpf(txtCpf.getText());
            usuario.setNome(txtNomeUsuario.getText());
            usuario.setLogin(txtLogin.getText());
            usuario.setSenha(txtSenha.getText());
            usuario.setId(new Integer(idUsuario.getText()));
            
            daoUsuario.edit(usuario);
            System.out.println("funcionou");
            this.dispose();
        } catch (IllegalOrphanException ex) {
            Logger.getLogger(EditarSetor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(EditarSetor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(EditarSetor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastroUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoCadastrarUsuario;
    private javax.swing.JButton botaoSalvarUsuario;
    private javax.swing.JTextField idUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton limparDadosUsuario;
    private javax.swing.JTextField txtCpf;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNomeUsuario;
    private javax.swing.JPasswordField txtSenha;
    // End of variables declaration//GEN-END:variables

    


    
}
